package com.danton.user.controller;

import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.danton.common.bean.CommonResponse;
import com.danton.common.utils.StringUtils;
import com.danton.framework.BaseController;
import com.danton.model.BsAdminModel;
import com.danton.model.BsAdminRoleModel;
import com.danton.model.BsPermissionModel;
import com.danton.model.BsRoleModel;
import com.danton.model.BsRolePermissionModel;
import com.danton.user.service.PermissionService;
import com.danton.user.service.RoleService;
import com.danton.user.service.UserService;
import com.danton.user.service.impl.PermissionServiceImpl;
import com.danton.user.service.impl.RoleServiceImpl;
import com.danton.user.service.impl.UserServiceImpl;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

public class RoleController extends BaseController {
	protected static final Logger logger = LoggerFactory.getLogger(RoleController.class);
	private RoleService roleService = enhance(RoleServiceImpl.class);// 支持事务处理
	private PermissionService permissionService = enhance(PermissionServiceImpl.class);// 支持事务处理
	private UserService userService = enhance(UserServiceImpl.class);// 支持事务处理

	public void list() {
		int pageNumber = getParaToInt("page_number", page_number);
		int pageSize = getParaToInt("page_size", page_size);
		Page<BsRoleModel> page = roleService.list(pageNumber, pageSize);
		List<BsRoleModel> list = page.getList();
		for (BsRoleModel bsRoleModel : list) {
			int role_id = bsRoleModel.get("id");
			List<BsPermissionModel> permission = permissionService.findByRoleID(role_id);
			bsRoleModel.put("permissoins", permission);
		}
		CommonResponse respones = CommonResponse.buildResponse();
		respones.getBody().put("page", page);
		renderJson(respones);
	}

	public void search() {
		int pageNumber = getParaToInt("page_number", page_number);
		int pageSize = getParaToInt("page_size", page_size);
		String kw = getPara("kw");
		Page<BsRoleModel> page = roleService.searchRole(pageNumber, pageSize, kw);
		List<BsRoleModel> list = page.getList();
		for (BsRoleModel bsRoleModel : list) {
			int role_id = bsRoleModel.get("id");
			List<BsPermissionModel> permission = permissionService.findRoleID(role_id);
			bsRoleModel.put("permissoins", permission);
		}
		CommonResponse respones = CommonResponse.buildResponse();
		respones.getBody().put("page", page);
		renderJson(respones);
	}

	public void add() {
		String code = getPara("code");
		String name = getPara("name");
		String remark = getPara("remark");
		String powers = getPara("powers") == null ? "," : getPara("powers");
		String[] powerids = powers.split(",");
		BsRoleModel roleModel = new BsRoleModel();
		roleModel.set("code", code).set("name", name).set("remark", remark);

		boolean flag = roleService.add(roleModel);
		String role_id = roleService.findId(name);
		if(Integer.parseInt(role_id)>=10){      //为角色code字段赋值，pearl系统用到
			roleModel.set("id", role_id);
			roleModel.set("code","R0"+role_id);
		}else{
			roleModel.set("id", role_id);
			roleModel.set("code","R00"+role_id);
		}
		roleService.edit(roleModel);
		if (StringUtils.isNotEmpty(role_id) && powerids.length >= 1) {
			List<BsRolePermissionModel> rplist = new ArrayList<BsRolePermissionModel>();
			roleService.deletePermissions(Integer.parseInt(role_id));// 先删除已关联权限
			for (int i = 0; i < powerids.length; i++) {
				BsRolePermissionModel rp = new BsRolePermissionModel();
				String permissionid = powerids[i];
				if (!"".equals(permissionid) && !"".equals(role_id)) {
					rp.set("role_id", role_id).set("permission_id", Integer.parseInt(permissionid));
				}
				rplist.add(rp);
			}
			roleService.relatePermissions(rplist);
		}
		CommonResponse respones = CommonResponse.buildResponse();
		respones.getBody().put("role_id", role_id);
		if (flag) {
			renderJson(respones);
		} else {
			renderJson(CommonResponse.buildResponse(1, "记录已经存在！"));// errno=1,记录已存在
		}
	}

	public void edit() {
		int role_id = getParaToInt("role_id") == null ? 0 : getParaToInt("role_id");
		String code = getPara("code");
		String name = getPara("name");
		String remark = getPara("remark");
		String powers = getPara("powers") == null ? "," : getPara("powers");
		String[] powerids = powers.split(",");

		BsRoleModel roleModel = new BsRoleModel();
		roleModel.set("id", role_id).set("code", code).set("name", name).set("remark", remark);
		boolean flag = roleService.edit(roleModel);

		if (powerids.length >= 1) { // 角色关联权限
			List<BsRolePermissionModel> rplist = new ArrayList<BsRolePermissionModel>();
			roleService.deletePermissions(role_id);// 先删除已关联权限
			for (int i = 0; i < powerids.length; i++) {
				BsRolePermissionModel rp = new BsRolePermissionModel();
				String permissionid = powerids[i];
				if (!"".equals(permissionid) && role_id != 0) {
					rp.set("role_id", role_id).set("permission_id", Integer.parseInt(permissionid));
				}
				rplist.add(rp);
			}
			roleService.relatePermissions(rplist);
		}

		if (flag) {
			renderJson(CommonResponse.buildResponse());
		} else {
			renderJson(CommonResponse.buildResponse(1, "记录已经存在！"));// errno=1,记录已存在
		}
	}

	public void relatePermissions() {
		int role_id = getParaToInt("role_id") == null ? 0 : getParaToInt("role_id");
		String permission_ids = getPara("permission_ids");
		String[] permission_id = permission_ids.split(",");

		// roleService.deletePermissions(role_id);// 先删除已关联权限

		List<BsRolePermissionModel> rplist = new ArrayList<BsRolePermissionModel>();
		for (int i = 0; i < permission_id.length; i++) {
			BsRolePermissionModel rp = new BsRolePermissionModel();
			String permissionid = permission_id[i];
			if (!"".equals(permissionid) && !"".equals(role_id)) {
				rp.set("role_id", role_id).set("permission_id", Integer.parseInt(permissionid));
			}
			rplist.add(rp);
		}
		roleService.relatePermissions(rplist);
		renderJson(CommonResponse.buildResponse());
	}

	public void relateUsers() {
		int role_id = getParaToInt("role_id") == null ? 0 : getParaToInt("role_id");
		String user_ids = getPara("user_ids").trim();
		String[] user_id = user_ids.split(",");
		List<BsAdminRoleModel> arlist = new ArrayList<BsAdminRoleModel>();
		for (int i = 0; i < user_id.length; i++) {
			BsAdminRoleModel ar = new BsAdminRoleModel();
			String userid = user_id[i];
			if (StringUtils.isNotEmpty(userid.trim())) {
				ar.set("role_id", role_id).set("admin_id", Integer.parseInt(userid));

			}
			arlist.add(ar);
		}
		userService.deleteUser(role_id);// 先删除角色已关联用户
		// roleService.deleteRoleAdminByUserId(user_ids); // 删除选中用户和以前角色的关联

		roleService.relateUsers(arlist);

		renderJson(CommonResponse.buildResponse());
	}

	public void listPermissions() {
		int role_id = getParaToInt("role_id") == null ? 0 : getParaToInt("role_id");
		List<BsPermissionModel> permissionlist = new ArrayList<BsPermissionModel>();
		if (!"".equals(role_id)) {
			permissionlist = permissionService.findRoleID(role_id);
		}
		CommonResponse respones = CommonResponse.buildResponse();
		respones.getBody().put("list", permissionlist);
		renderJson(respones);
	}

	public void getRoleById() {
		int role_id = getParaToInt("role_id") == null ? 0 : getParaToInt("role_id");
		BsRoleModel role = roleService.getRoleById(role_id);
		CommonResponse respones = CommonResponse.buildResponse();
		respones.getBody().put("role", role);
		renderJson(respones);
	}

	/*
	 * 查询所有权限(通过模块分组)
	 */
	public void listAllPermissionsByModule() {
		List<Record> list = new ArrayList<Record>();
		List<Record> modulelist = permissionService.listAllModule(); // 查询所有模块
		List<BsPermissionModel> permissionlist = new ArrayList<BsPermissionModel>();
		if (modulelist != null && modulelist.size() > 0) {
			int i = 60000; // 防止重复
			for (Record re : modulelist) {
				String module = re.getStr("module");
				Record record = new Record();
				if (StringUtils.isNotEmpty(module)) {
					permissionlist = permissionService.listAllPermissionByModule(module);
				}
				record.set("module", module).set("permissionlist", permissionlist).set("id", i);
				i++;
				list.add(record);
			}
		}
		CommonResponse respones = CommonResponse.buildResponse();
		respones.getBody().put("list", list);
		renderJson(respones);
	}

	/*
	 * 查询角色已关联权限(通过模块分组)
	 */
	public void listRolePermissionsByModule() {
		List<Record> list = new ArrayList<Record>();
		int role_id = getParaToInt("role_id") == null ? 0 : getParaToInt("role_id");
		List<Record> modulelist = permissionService.listRoleModule(role_id); // 查询所有模块
		List<BsPermissionModel> permissionlist = new ArrayList<BsPermissionModel>();
		if (modulelist != null && modulelist.size() > 0) {
			int i = 60000; // 防止重复
			for (Record re : modulelist) {
				String module = re.getStr("module");
				Record record = new Record();
				if (StringUtils.isNotEmpty(module)) {
					permissionlist = permissionService.listRolePermissionByModule(role_id, module);
				}
				record.set("module", module).set("permissionlist", permissionlist).set("id", i);
				list.add(record);
				i++;
			}
		}
		CommonResponse respones = CommonResponse.buildResponse();
		respones.getBody().put("list", list);
		renderJson(respones);
	}

	public void listUsers() {
		int role_id = getParaToInt("role_id") == null ? 0 : getParaToInt("role_id");
		List<BsAdminModel> userlist = new ArrayList<BsAdminModel>();
		if (!"".equals(role_id)) {
			userlist = userService.findUserByRoleID(role_id);
		}
		CommonResponse respones = CommonResponse.buildResponse();
		respones.getBody().put("list", userlist);
		renderJson(respones);
	}

	public void lock() {
		int role_id = getParaToInt("role_id") == null ? 0 : getParaToInt("role_id");
		// String name=getPara("name")==null?"":getPara("name");
		BsRoleModel roleModel = new BsRoleModel();
		roleModel.set("id", role_id).set("status", 1);
		roleService.editRoleStatus(roleModel);
		renderJson(CommonResponse.buildResponse());
	}

	public void unlock() {
		int role_id = getParaToInt("role_id") == null ? 0 : getParaToInt("role_id");
		// String name=getPara("name")==null?"":getPara("name");
		BsRoleModel roleModel = new BsRoleModel();
		roleModel.set("id", role_id).set("status", 0);
		roleService.editRoleStatus(roleModel);
		renderJson(CommonResponse.buildResponse());
	}

	public boolean roleStatusCheck(int role_id) {
		return roleService.roleStatusCheck(role_id);
	}
}
